<?php

namespace app\common\helper;

use app\common\model\User;
use app\common\model\UserToken;
use think\exception\HttpResponseException;
use think\helper\Str;

class TokenHelper
{
    private static $salt = "htidc_net";
    public static function getUserByToken($token)
    {
        $token = md5(self::$salt . $token . self::$salt);
        $user_token = UserToken::where('token',$token)->find();
        if ($user_token) {
            if ($user_token->getData('expired_time') > time()) {
                $user =  User::where("id",$user_token->user_id)->find();
                if ($user) {
                    return  $user;
                }
            } else {
                $user_token->delete();
            }
        }
        throw new HttpResponseException(json([
            "code" => 401,
            "msg" => "请先登录"
        ]));
    }
}